package com.dennytech.tac.ui.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.dennytech.tac.R;
import com.dennytech.tac.base.BasicAdapter;
import com.dennytech.tac.base.CFActivity;
import com.dennytech.tac.model.Channel;
import com.dennytech.tac.statistics.Stat;
import com.dennytech.tac.ui.adapter.GridPagerAdapter;
import com.dennytech.tac.utils.db.ChannelDBHelper;
import com.dennytech.tac.widget.AnimationLayout;
import com.dennytech.tac.widget.AnimationLayout.Listener;
import com.dennytech.tac.widget.NetworkImageView;

public class MainActivityV2 extends CFActivity implements Listener,
		OnPageChangeListener, OnClickListener {

	private static final String ACTION_CHANNEL_CHANGED = "com.dennytech.tac.action.CHANNEL_CHANGED";

	AnimationLayout mLayout;
	ViewPager mPager;
	GridPagerAdapter mPagerAdapter;
	View mSetting;
	TextView mPageNumTv;
	int mPageNum;

	final Object ADD = new Object();

	private List<GridView> gridViews;

	private BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (ACTION_CHANNEL_CHANGED.equals(intent.getAction())) {
				resetGridView();
			}
		}
	};

	@Override
	protected void initView() {
		setContentView(R.layout.layout_main);

		mLayout = (AnimationLayout) findViewById(R.id.animation_layout);
		mLayout.setListener(this);

		mPager = (ViewPager) findViewById(R.id.main_pager);
		mPager.setOnPageChangeListener(this);
		mSetting = findViewById(R.id.main_setting);
		mPageNumTv = (TextView) findViewById(R.id.main_page_num);

		mSetting.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mLayout.isOpening()) {
					mLayout.closeSidebar();
				} else {
					mLayout.openSidebar();
				}
			}
		});
		findViewById(R.id.setting_help).setOnClickListener(this);
		findViewById(R.id.setting_share).setOnClickListener(this);
		findViewById(R.id.setting_feedback).setOnClickListener(this);
		findViewById(R.id.setting_about).setOnClickListener(this);

		resetGridView();
	}

	@Override
	protected void onCreate(Bundle b) {
		super.onCreate(b);

		IntentFilter filter = new IntentFilter(ACTION_CHANNEL_CHANGED);
		registerReceiver(receiver, filter);
	}

	@Override
	protected void onDestroy() {
		unregisterReceiver(receiver);
		super.onDestroy();
	}

	private void resetGridView() {
		List<Object> dataList = new ArrayList<Object>();
		dataList.add(new GridItem(getString(R.string.tab_name_timeline),
				"denny://timeline", "ic_travel_note.png"));
		dataList.add(new GridItem(getString(R.string.tab_name_togo),
				"denny://mycollect", "ic_my_collect.png"));

		List<Channel> channels = ChannelDBHelper.instance().query();
		if (channels != null) {
			for (Channel channel : channels) {
				dataList.add(new GridItem(channel.getName(),
						"denny://talist?title=" + channel.getName() + "&id="
								+ channel.getId(), channel.getPhotoUrl()));
			}
		}

		dataList.add(ADD);
		addPage(dataList);
	}

	private void addPage(List<Object> data) {
		mPageNum = data.size() % 6 == 0 ? (data.size() / 6)
				: (data.size() / 6 + 1);
		mPageNumTv.setText(1 + "/" + mPageNum);

		gridViews = new ArrayList<GridView>();
		for (int i = 0; i < mPageNum; i++) {
			GridView gridView = (GridView) getLayoutInflater().inflate(
					R.layout.layout_main_grid, null, false);
			gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));

			MyGridAdapter gridAdapter = new MyGridAdapter();
			List<Object> pageData = new ArrayList<Object>();
			int pageItemsNum = i == (mPageNum - 1) ? (data.size() - i * 6) : 6;
			for (int j = 0; j < pageItemsNum; j++) {
				pageData.add(data.get(j + i * 6));
			}
			gridAdapter.setData(pageData);
			gridView.setAdapter(gridAdapter);
			gridView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					Object item = parent.getItemAtPosition(position);
					if (item == ADD) {
						try {
							startActivity(new Intent(Intent.ACTION_VIEW, Uri
									.parse("denny://channellist")));

							Stat.event("main", "main_grid_item_click",
									"channel list", 0);

						} catch (Exception e) {
						}

					} else if (item instanceof GridItem) {
						try {
							startActivity(new Intent(Intent.ACTION_VIEW, Uri
									.parse(((GridItem) item).uri)));

							Stat.event("main", "main_grid_item_click",
									((GridItem) item).title, 0);

						} catch (Exception e) {
						}
					}
				}
			});

			gridViews.add(gridView);
		}
		mPagerAdapter = new GridPagerAdapter(gridViews);
		mPager.setAdapter(mPagerAdapter);
		mPagerAdapter.notifyDataSetChanged();
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.setting_feedback) {
			Intent email = new Intent(Intent.ACTION_SENDTO,
					Uri.parse("mailto:"));
			String[] emailReciver = new String[] { "dengjun86@gmail.com" };
			String emailSubject = getString(R.string.label_feedback_subject);
			String emailBody = getString(R.string.label_feedback_default_body);

			email.putExtra(Intent.EXTRA_EMAIL, emailReciver);
			email.putExtra(Intent.EXTRA_SUBJECT, emailSubject);
			email.putExtra(Intent.EXTRA_TEXT, emailBody);

			try {
				startActivity(email);
			} catch (Exception e) {
				Toast.makeText(this,
						getString(R.string.label_feedback_no_email_client),
						Toast.LENGTH_SHORT).show();
			}

			Stat.event("setting", "setting_feedback", null, 0);

		} else if (v.getId() == R.id.setting_about) {
			Intent intent = new Intent(Intent.ACTION_VIEW,
					Uri.parse("denny://about"));
			startActivity(intent);

			Stat.event("setting", "setting_share", null, 0);
		} else if (v.getId() == R.id.setting_share) {
			Intent intent = new Intent(Intent.ACTION_SEND);
			intent.setType("text/plain");
			intent.putExtra(Intent.EXTRA_SUBJECT,
					getText(R.string.label_recommend_subject));
			intent.putExtra(Intent.EXTRA_TEXT,
					getText(R.string.label_recommend_text));
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(Intent.createChooser(intent,
					getString(R.string.share)));

			Stat.event("setting", "setting_share", null, 0);
		} else if (v.getId() == R.id.setting_help) {
			String country = Locale.getDefault().getCountry();
			boolean isCN = country != null && country.contains("CN");
			String url = "http://www.dennytech.com/help" + (isCN ? "_cn" : "");
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setData(Uri.parse(url));
			startActivity(intent);

			Stat.event("setting", "setting_help", null, 0);
		}
	}

	@Override
	public void onBackPressed() {
		if (mLayout.isOpening()) {
			mLayout.closeSidebar();
		} else {
			finish();
		}
	}

	@Override
	public void onSidebarOpened() {

	}

	@Override
	public void onSidebarClosed() {

	}

	@Override
	public boolean onContentTouchedWhenOpening() {
		mLayout.closeSidebar();
		return true;
	}

	class GridItem {
		String title;
		String uri;
		String image;

		public GridItem(String title, String uri, String image) {
			this.title = title;
			this.uri = uri;
			this.image = image;
		}
	}

	class MyGridAdapter extends BasicAdapter {

		List<Object> mData;

		public void setData(List<Object> data) {
			mData = data;
		}

		@Override
		public int getCount() {
			if (mData == null) {
				return 1;
			}
			return mData.size();
		}

		@Override
		public Object getItem(int position) {
			if (mData == null) {
				return ADD;
			}
			return mData.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Object item = getItem(position);
			View view = convertView;
			if (view == null) {
				view = getLayoutInflater().inflate(R.layout.grid_item, parent,
						false);
			}

			int pHight = mPager.getHeight() - 180;
			GridView.LayoutParams params = new GridView.LayoutParams(
					LayoutParams.MATCH_PARENT, pHight / 3);
			view.setLayoutParams(params);

			NetworkImageView icon = (NetworkImageView) view
					.findViewById(android.R.id.icon);
			TextView title = (TextView) view.findViewById(android.R.id.text1);

			if (item != ADD) {
				GridItem gridItem = (GridItem) item;
				view.setBackgroundResource(R.drawable.clickable_trans_gray);
				icon.setImage(gridItem.image);
				title.setText(gridItem.title);
				title.setVisibility(View.VISIBLE);

			} else {
				view.setBackgroundResource(R.drawable.clickable_trans_light_gray);
				icon.setImage("icon_add.png");
				title.setVisibility(View.GONE);
			}
			return view;
		}

	}

	@Override
	public void onPageScrollStateChanged(int arg0) {
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
	}

	@Override
	public void onPageSelected(int arg0) {
		mPageNumTv.setText((arg0 + 1) + "/" + mPageNum);
	}
}
